// to enable CCLOG()
#define COCOS2D_DEBUG 1

#include "cocos2d.h"
#include "FileOperation.h"
#include <stdio.h>
#include "Config.h"

using namespace std;

void FileOperation::fSaveFile(std::string fileName)
{
	string path = fGetFilePath(fileName);

	FILE *fp = fopen(path.c_str(), "w");

	if (! fp)
	{
		CCLOG("can not create file %s", path.c_str());

		return;
	}

	//fputs("file example", fp);

	fclose(fp);
}

void FileOperation::fReadFile(std::string fileName)
{
	string path = fGetFilePath(fileName);

	FILE *fp = fopen(path.c_str(), "r");

	char buf[50] = {0};

	if (! fp)
	{
		CCLOG("can not open file %s", path.c_str());

		return;
	}

	fgets(buf, 50, fp);

	CCLOG("read content %s", buf);

	fclose(fp);
}

FILE* FileOperation::fGetFile(std::string fileName, char* mode)
{
	string path = fGetFilePath(fileName);

	FILE *fp = fopen(path.c_str(), mode);

	if (! fp)
	{
		CCLOG("can not get file %s", path.c_str());

		return NULL;
	}

	return fp;
}


int FileOperation::fGetTopScore(std::string fileName)
{
	FILE* fp = fGetFile(fileName, kFileModeRead);

	if(!fp)
	{
		return -1;
	}

	char buff[100] = {0};

	fgets(buff, 100, fp);

	std::stringstream str(buff); 

	int myScore;  

	str >> myScore;

	if (!str) 
	{      
		// The conversion failed.
		CCLOG("convert char to int failed");

		return -1;
	} 

	return myScore;
}

void FileOperation::fSetTopScore(string fileName, int score)
{
	FILE* fp = fGetFile(fileName, kFileModeWrite);

	if(!fp)
	{
		return;
	}

	stringstream ss;

	// add score to stringstream
	ss << score;

	if(fputs(ss.str().c_str(), fp))
	{
		CCLOG("write file success");
	}

	fclose(fp);
}


string FileOperation::fGetFilePath(std::string fileName)
{
	string path("");

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
	// In android, every programe has a director under /data/data.
	// The path is /data/data/ + start activity package name.
	// You can save application specific data here.
	path.append(kPathAndroid+fileName);
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
	// You can save file in anywhere if you have the permision.
	path.append(kPathWin32+fileName);
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE)
	path = cocos2d::CCApplication::sharedApplication().getAppDataPath();

#ifdef _TRANZDA_VM_
	// If runs on WoPhone simulator, you should insert "D:/Work7" at the
	// begin. We will fix the bug in no far future.
	path = "D:/Work7" + path;
	path.append(fileName);
#endif

#endif

	return path;
}